package com.dituhui.gps.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;

import com.dituhui.gps.vo.GPSPoint;
import com.dituhui.tool.io.RedisTool;
import com.dituhui.tool.util.StringUtil;

/**
 * 获取GPS位置
 * 
 * @author liweigu
 *
 */
public class GetPos {
	private static Logger LOGGER = Logger.getLogger(GetPos.class);
	private static final String Redis_Pos_Prefix = "pos_";

	public static String getRedisKey(String accountId, String groupId) {
		String redisKey;

		// if (groupId == null) {
		redisKey = GetPos.Redis_Pos_Prefix + accountId;
		// } else {
		// redisKey = GetPos.Redis_Pos_Prefix + groupId + StringUtil.Underline + accountId;
		// }

		return redisKey;
	}

	public static GPSPoint getGPS(String accountId, String groupId, String redisHost, int redisPort, String redisPassword) {
		RedisTool redisTool = new RedisTool();
		String redisKey = GetPos.getRedisKey(accountId, groupId);
		String value = redisTool.getString(redisKey, redisHost, redisPort, redisPassword);
		GPSPoint gpsPoint = GPSPoint.parseCSVString(value);
		// TODO: 根据groupId筛选
		return gpsPoint;
	}

	public static List<GPSPoint> getGPSList(String groupId, String redisHost, int redisPort, String redisPassword) {
		List<GPSPoint> gpsPoints = new ArrayList<GPSPoint>();

		RedisTool redisTool = new RedisTool();
		String keysQueryClause;
		// if (groupId == null) {
		keysQueryClause = Redis_Pos_Prefix + "*";
		// } else {
		// keysQueryClause = Redis_Pos_Prefix + groupId + StringUtil.Underline + "*";
		// }
		// System.out.println("redisHost = " + redisHost);
		// System.out.println("redisPort = " + redisPort);
		Set<String> redisKeys = redisTool.getKeys(keysQueryClause, redisHost, redisPort, redisPassword);
		for (String redisKey : redisKeys) {
			String value = redisTool.getString(redisKey, redisHost, redisPort, redisPassword);
			GPSPoint gpsPoint = GPSPoint.parseCSVString(value);
			// TODO: 根据groupId筛选
			if (groupId == null || groupId.equals(gpsPoint.getGroupId())) {
				gpsPoints.add(gpsPoint);
			}
		}

		return gpsPoints;
	}
}
